package com.ry.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ry.common.Constants;
import com.ry.dao.UserDao;
import com.ry.model.dto.UserDTO;
import com.ry.model.entity.User;
import com.ry.service.TokenService;
import com.ry.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author ry
 * @since 2021-11-09 17:21
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Autowired
    private TokenService tokenService;

    @Override
    public UserDTO getUserByOpenId(User user){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",user.getOpenId());
        User queryUser = userDao.selectOne(queryWrapper);
        if (ObjectUtils.isEmpty(queryUser)){
            //用户为空
            return null;
        }else {
            queryUser.setSessionKey(user.getSessionKey());
            return userToUserDTO(queryUser);
        }
    }

    @Override
    public UserDTO register(User user){
        userDao.insert(user);

        return userToUserDTO(user);
    }

    @Override
    public UserDTO getUserById(Integer id) {
        User user = userDao.selectById(id);
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setNickname(user.getNickname());
        userDTO.setAvatarUrl(user.getAvatarUrl());
        userDTO.setCoverUrl(user.getCoverUrl());
        userDTO.setMotto(user.getMotto());
        userDTO.setGender(user.getGender());
        //不是登录，不应该更新token
//        userDTO.setToken();



        return userDTO;
    }

    private UserDTO userToUserDTO(User user){
        String token = tokenService.login(user);

        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setNickname(user.getNickname());
        userDTO.setAvatarUrl(user.getAvatarUrl());
        userDTO.setCoverUrl(user.getCoverUrl());
        userDTO.setMotto(user.getMotto());
        userDTO.setGender(user.getGender());
        userDTO.setToken(token);

        return userDTO;
    }
}
